package com.wunong.smart.algorithm.simple.heap;

import java.util.Collection;
import java.util.Deque;
import java.util.Objects;

/**
 * 顶堆
 *
 * @author created by zealot.zt
 */
public class TopHeap<T> {

    /**
     * 队列
     */
    private final Deque<T> deque;

    /**
     * 栈
     */
    private final Stackable<T> stackable;

    public TopHeap(Deque<T> deque, Stackable<T> stackable) {
        Objects.requireNonNull(deque, "deque can't be null");
        Objects.requireNonNull(stackable, "stackable can't be null");
        this.deque = deque;
        this.stackable = stackable;
    }

    /**
     * push所有元素
     *
     * @param c
     */
    public void pushAll(Collection<T> c) {
        for (T ele : c) {
            this.push(ele);
        }
    }

    /**
     * 入栈
     *
     * @param ele 元素
     */
    public void push(T ele) {
        if (isEmpty()) {
            deque.push(ele);
            return;
        }

        // 栈顶元素
        T top = peek();
        if (stackable.needPush(ele, top)) {
            deque.push(ele);
        }
    }

    /**
     * 获取栈顶
     *
     * @return
     */
    public T peek() {
        return deque.peek();
    }

    /**
     * 出栈
     *
     * @return
     */
    public T pop() {
        return deque.pop();
    }

    /**
     * 是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return deque.isEmpty();
    }

    /**
     * 是否存在元素
     *
     * @return
     */
    public boolean hasElements() {
        return !isEmpty();
    }

}
